package com.zadtek.shopmall.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.activities.MainActivity;
import com.zadtek.shopmall.activities.SubmitOrderActivity;
import com.zadtek.shopmall.adapter.ShopCartAdapter;
import com.zadtek.shopmall.base.AbsFragment;
import com.zadtek.shopmall.bean.BuyingProductHeaderItem;
import com.zadtek.shopmall.bean.GuesLikeProductItem;
import com.zadtek.shopmall.bean.HomeBaseBean;
import com.zadtek.shopmall.bean.MultiItem;
import com.zadtek.shopmall.bean.OperateResponseBean3;
import com.zadtek.shopmall.bean.ShopCartData;
import com.zadtek.shopmall.bean.ShopCartProductItem;
import com.zadtek.shopmall.bean.ShopcartDataBean;
import com.zadtek.shopmall.net.BaseObserver;
import com.zadtek.shopmall.net.BaseResponse;
import com.zadtek.shopmall.net.NetTool;
import com.zadtek.shopmall.other.Const;
import com.zadtek.shopmall.utils.ToastUtil;
import com.zadtek.shopmall.view.GridSpacingItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Zackv on 2018/4/2.
 */

public class ShopCartFragment extends AbsFragment {
    private LinearLayout linearLayout;
    private RecyclerView recyclerView;
    private View emptyView;
    private LinearLayout adviceProductContainer;
    private TextView goToSee,submitOrder,totalPrice;
    private CheckBox selectAll;

    private ShopCartAdapter shopCartAdapter;
    private List<ShopCartData> serverShopData = new LinkedList<>();
    private List<GuesLikeProductItem> serverProductData = new LinkedList<>();
    private List<MultiItem> uiDataList = new LinkedList<>();
    private ShopcartDataBean shopcartDataBean;
    private HashMap<Integer,List<Integer>> map = new HashMap();


    @Override
    public int setView() {
        return R.layout.fragment_shop_cart;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initView();
        initLogic();
        requestData();
        //initData();
        //updateView();
    }

    private void requestData() {
        Map<String, Object> param = NetTool.newParams();
        //final Map<String, Object> params = new ArrayMap<String, Object>();
        param.put("uid", 44);
        NetTool.getApi().getShopCartData(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<List<ShopCartData>>>(this) {
                    @Override
                    public void onData(BaseResponse<List<ShopCartData>> value) {
                        if(value.getCode() == 0 ){
                            serverShopData.addAll(value.getData());
                            updateView();
                        }
                    }
                });
        NetTool.getApi().getLike(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<List<GuesLikeProductItem>>>() {
                    @Override
                    public void onData(BaseResponse<List<GuesLikeProductItem>> value) {
                        if(value.getCode() == 0 && value.getData()!=null){
                            serverProductData.addAll(value.getData());
                            updateView();
                        }
                    }
                });
    }

    private void updateView() {
        if(!serverShopData.isEmpty()){
            updateList();
        }else{
            updateEmptyView();
        }
    }

    private void updateEmptyView() {
        linearLayout.setVisibility(View.GONE);
/*        for(int i=0;i<shopcartDataBean.getAdviceProductList().size();i++){
            View v = getLayoutInflater().inflate(R.layout.product_item,null);
            ImageView productImg = (ImageView) v.findViewById(R.id.product_img);
            TextView productTitle = (TextView) v.findViewById(R.id.product_title);
            TextView productSales = (TextView) v.findViewById(R.id.product_sales);
            TextView productPrice = (TextView) v.findViewById(R.id.product_price);

            productSales.setVisibility(View.GONE);

            productPrice.setText(shopcartDataBean.getAdviceProductList().get(i).getProductPrice());
            final int finalI = i;
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToastUtil.showToast(finalI+"");
                }
            });
            adviceProductContainer.addView(v);
        }*/
    }

    private void updateList() {
        uiDataList.clear();
        linearLayout.setVisibility(View.VISIBLE);
        for(int i =0;i<serverShopData.size();i++){
            BuyingProductHeaderItem item = new BuyingProductHeaderItem(serverShopData.get(i).getRu_name());
            item.setType(Const.SHOP);
            item.setId(serverShopData.get(i).getRu_id());
            item.setSelfSell(serverShopData.get(i).isSelfSell());

            uiDataList.add(new MultiItem(MultiItem.Type_Car_Product_header,item));
            int headerPosition = uiDataList.size()-1;
            List<ShopCartProductItem> list = serverShopData.get(i).getGoods_list();
            List<Integer> integers = new ArrayList<>();
            for(int j=0;j<list.size();j++){
                uiDataList.add(new MultiItem(MultiItem.Type_Car_Product,list.get(j)));
                integers.add(uiDataList.size()-1);
            }
            map.put(headerPosition,integers);
        }
        if(serverProductData.size() > 0){
            uiDataList.add(new MultiItem(MultiItem.Type_Home_Header,""));
            int skipItem = uiDataList.size();
            recyclerView.addItemDecoration(new GridSpacingItemDecoration(skipItem,2,getResources().getDimensionPixelSize(R.dimen.little_margin), true));
            for(GuesLikeProductItem item:serverProductData){
                uiDataList.add(new MultiItem(MultiItem.Type_Product,item));
            }
        }
        shopCartAdapter.notifyDataSetChanged();
    }

//    private void initData() {
//        IndexProductItem indexProductItem = new IndexProductItem();
//        indexProductItem.setProductPrice("￥59.00");
//        indexProductItem.setProductTitle("媞沫 2014夏装新品女装 宽松假两件蝙蝠短袖印花雪纺衫 粉色 S");
//        indexProductItem.setProductImgUrl("http://tc.zadtek.com/aaa/images/201512/thumb_img/7_thumb_G_1450120026360.jpg");
//        indexProductItem.setId(94759348);
//        indexProductItem.setType(Const.PRODUCT);
//
//        IndexProductItem indexProductItem2 = new IndexProductItem();
//        indexProductItem2.setProductPrice("￥168.00");
//        indexProductItem2.setProductTitle("卡莎度(CASATO)防蓝光防辐射眼镜电脑护目眼镜抗疲劳男女款ME2721 全黑色ME2721");
//        indexProductItem2.setProductImgUrl("http://tc.zadtek.com/aaa/images/201407/thumb_img/61_thumb_G_1405019283133.jpg");
//        indexProductItem.setId(87687);
//        indexProductItem.setType(Const.PRODUCT);
//
//        serverProductData.add(indexProductItem);
//        serverProductData.add(indexProductItem2);
//        serverProductData.add(indexProductItem);
//        serverProductData.add(indexProductItem2);
//        serverProductData.add(indexProductItem);
//        serverProductData.add(indexProductItem2);
//        serverProductData.add(indexProductItem);
//
//        ShopCartData shopCartData = new ShopCartData();
//        shopCartData.setShopName("5+旗舰店");
//        List<ShopCartData.BuyingProductItem> tList = new LinkedList<>();
//        ShopCartData.BuyingProductItem item = new ShopCartData.BuyingProductItem();
//        item.setProductTitle("丹顿公子【都市系列】男士西裤 英伦修身休闲西装裤夏季薄款商务职业正装 黑色竖纹款 29码");
//        item.setProductPrice(534.00);
//        item.setProductDesc("选择颜色:黑色竖纹款[¥2.20] 选择尺码:28[¥1.30] ");
//        item.setProductImgUrl("http://tc.zadtek.com/aaa/images/201512/thumb_img/163_thumb_G_1450309107382.jpg");
//        item.setSelected(false);
//        item.setCount(1);
//        item.setId(454345);
//        item.setType(Const.PRODUCT);
//
//        ShopCartData.BuyingProductItem item2 = new ShopCartData.BuyingProductItem();
//        item2.setProductTitle("神州笔记本");
//        item2.setProductPrice(9999.00);
//        item2.setProductDesc("已选择黑色");
//        item2.setSelected(false);
//        item2.setCount(1);
//
//        tList.add(item);
//        shopCartData.setBuyingProductItemList(tList);
//
//        ShopCartData shopCartData2 = new ShopCartData();
//        shopCartData2.setShopName("商创自营");
//        List<ShopCartData.BuyingProductItem> tList2 = new LinkedList<>();
//        ShopCartData.BuyingProductItem item3 = new ShopCartData.BuyingProductItem();
//        item3.setProductTitle("豪韵IA-6120HD高清5.1家庭影院音响功放组合套装蓝牙解码壁挂家用电视回音壁音箱");
//        item3.setProductPrice(3000.00);
//        item3.setProductDesc("");
//        item3.setProductImgUrl("http://tc.zadtek.com/aaa/images/201603/thumb_img/529_thumb_G_1457132805624.jpg");
//        item3.setSelected(false);
//        item3.setCount(1);
//        item3.setId(5464564);
//        item3.setType(Const.PRODUCT);
//
//        ShopCartData.BuyingProductItem item4 = new ShopCartData.BuyingProductItem();
//        item4.setProductTitle("鲫鱼");
//        item4.setProductPrice(9999.00);
//        item4.setProductDesc("已选择黑色");
//        item4.setSelected(false);
//        item4.setCount(1);
//
//        tList2.add(item3);
//
//        shopCartData2.setBuyingProductItemList(tList2);
//        serverShopData.add(shopCartData);
//        serverShopData.add(shopCartData2);
//        shopcartDataBean = new ShopcartDataBean();
//        shopcartDataBean.setAdviceProductList(serverProductData);
//        shopcartDataBean.setBuyingProductList(serverShopData);
//
//        BaseResponse<ShopcartDataBean> baseResponse = new BaseResponse<>();
//        baseResponse.setData(shopcartDataBean);
//        baseResponse.setCode(0);
//        baseResponse.setMessage("");
//        Gson gson = new Gson();
//        String json = gson.toJson(baseResponse);
//    }

    private void initLogic() {
        selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!compoundButton.isPressed()) {
                    return;
                }
                for(MultiItem item:uiDataList){
                    if(item.getItemType() == MultiItem.Type_Car_Product || item.getItemType() == MultiItem.Type_Car_Product_header){
                        item.setSelected(b);
                        caculateTotalPrice();
                    }else{
                        break;
                    }
                }
                shopCartAdapter.notifyDataSetChanged();
            }
        });
        shopCartAdapter = new ShopCartAdapter(mActivity,uiDataList);
        shopCartAdapter.setEmptyView(emptyView);
        recyclerView.setAdapter(shopCartAdapter);
        shopCartAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MultiItem item = uiDataList.get(position);
                switch (item.getItemType()){
                    case MultiItem.Type_Car_Product_header:
                        BuyingProductHeaderItem item1 = (BuyingProductHeaderItem) item.getData();
                        if(!item1.isSelfSell()){
                            Const.jumpHandle(mActivity, (HomeBaseBean) item.getData());
                        }
                        break;
                    case MultiItem.Type_Car_Product:
                        //Const.jumpHandle(mActivity, (HomeBaseBean) item.getData());
                        break;
                    case MultiItem.Type_Product:
                        //Const.jumpHandle(mActivity, (HomeBaseBean) item.getData());
                        break;
                }
            }
        });
        shopCartAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.cb_choose:
                        boolean isSelected = uiDataList.get(position).isSelected();
                        uiDataList.get(position).setSelected(!isSelected);
                        while (uiDataList.get(position).getItemType()!=MultiItem.Type_Car_Product_header)position--;
                        selectedChanged(position,false);
                        break;
                    case R.id.btn_add:
                        int count =((ShopCartProductItem) uiDataList.get(position).getData()).getGoods_number();
                        ((ShopCartProductItem) uiDataList.get(position).getData()).setGoods_number(++count);
                        break;
                    case R.id.btn_remove:
                        int count2 =((ShopCartProductItem) uiDataList.get(position).getData()).getGoods_number();
                        if(count2>1){
                            ((ShopCartProductItem) uiDataList.get(position).getData()).setGoods_number(--count2);
                        }
                        break;
                    case R.id.btn_delete:
                        deleteCart(position);
                        break;
                    case R.id.cb_choose_all_shop:
                        boolean isSelected2 = uiDataList.get(position).isSelected();
                        uiDataList.get(position).setSelected(!isSelected2);
//                        for(int i = position+1;i<uiDataList.size();i++){
//                            if(uiDataList.get(i).getItemType()!=MultiItem.Type_Product){
//                                break;
//                            }else{
//                                uiDataList.get(i).setSelected(!isSelected2);
//                            }
//                        }
                        selectedChanged(position,true);
                        break;
                }
                caculateTotalPrice();
                shopCartAdapter.notifyDataSetChanged();
            }
        });
        submitOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, SubmitOrderActivity.class));
            }
        });

        goToSee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((MainActivity)mActivity).show(0);
            }
        });

    }

    private void deleteCart(final int position) {
        Map<String, Object> para = NetTool.newParams();
        ShopCartProductItem item = (ShopCartProductItem) uiDataList.get(position).getData();
        para.put("id",item.getRec_id());
        NetTool.getApi().delete_cart(para).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new BaseObserver<BaseResponse<OperateResponseBean3>>() {
                    @Override
                    public void onData(BaseResponse<OperateResponseBean3> value) {
                        if(value.getCode() == 0 && value.getData()!=null){
                            if(value.getData().getError() == 0){
                                uiDataList.get(position).setDeleted(true);
                                int temp = position;
                                while (uiDataList.get(temp).getItemType()!=MultiItem.Type_Car_Product_header)temp--;
                                selectedChanged(temp,false);
                                shopCartAdapter.notifyDataSetChanged();
                            }else{
                                ToastUtil.showToast("删除失败！");
                            }
                        }
                    }
                });

    }

    private void selectedChanged(int headerPos,boolean fromHeaderChange) {
        List<Integer> list = map.get(headerPos);
        if(fromHeaderChange){
            for(Integer i:list){
                uiDataList.get(i).setSelected(uiDataList.get(headerPos).isSelected());
            }
        }else{
            boolean selectedHeader = true;
            boolean deleteHeader = true;
            for(Integer i:list){
                if(!uiDataList.get(i).isSelected() && !uiDataList.get(i).isDeleted()){
                    selectedHeader = false;
                }
                if(!uiDataList.get(i).isDeleted()){
                    deleteHeader = false;
                }
            }
            uiDataList.get(headerPos).setSelected(selectedHeader);
            uiDataList.get(headerPos).setDeleted(deleteHeader);
        }
        //check chosseAll


        boolean isEmpty = true;
        boolean chooseAll = true;
        for(Map.Entry<Integer,List<Integer>> entry:map.entrySet()){
            if(!uiDataList.get(entry.getKey()).isDeleted()){
                isEmpty = false;
            }
            if(!uiDataList.get(entry.getKey()).isSelected()){
                chooseAll = false;
            }
        }
        selectAll.setChecked(chooseAll);
        if(isEmpty) {
            uiDataList.clear();
            updateEmptyView();
        }
    }

    private void caculateTotalPrice() {
        double price = 0;
        for(MultiItem item:uiDataList){
            if(item.getItemType() == MultiItem.Type_Car_Product && item.isSelected() && !item.isDeleted()){
                ShopCartProductItem buyingProductItem = (ShopCartProductItem) item.getData();
                String p = buyingProductItem.getGoods_price().substring(1);
                float pr = Float.parseFloat(p);
                price = price + pr * buyingProductItem.getGoods_number();
            }
        }
        totalPrice.setText(String.valueOf(price));
    }

    private void initView() {
        linearLayout = (LinearLayout) findViewById(R.id.ll_price_container);
        recyclerView = (RecyclerView) findViewById(R.id.recycleview);
        GridLayoutManager layoutManager = new GridLayoutManager(mActivity,2);
        recyclerView.setLayoutManager(layoutManager);
        //recyclerView.addItemDecoration(new GridSpacingItemDecoration(2,getResources().getDimensionPixelSize(R.dimen.little_margin), false));
        totalPrice = (TextView) findViewById(R.id.tv_total_money);
        submitOrder = (TextView) findViewById(R.id.tv_submit_order);
        selectAll = (CheckBox) findViewById(R.id.cb_choose_all);
        getEmptyView();
    }

    private void getEmptyView() {
        emptyView = getLayoutInflater().inflate(R.layout.empty_view,null);
        adviceProductContainer = (LinearLayout) emptyView.findViewById(R.id.ll_container);
        goToSee = (TextView) emptyView.findViewById(R.id.tv_go_to_see);

    }
}
